package com.example.administrator.myapplication.heart;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.app.Fragment;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.tools.Whewview;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;


public class heart_heartrate_Fragment extends Fragment implements SurfaceHolder.Callback {

    private static final String TAG="Heartrate";
    private Toolbar toolbar;
    private ImageView iv_heartrate_videotape;
    private Camera.AutoFocusCallback mAutoFocusCallback=null;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private Camera myCamera;
    private Camera.Parameters myParameters;
    private MediaRecorder mRecorder;
    private Boolean isView=false;
    private boolean mStartedFlg = false;
    private TextView tv_bmp_start;
    private TextView tv_bmp_value;
    private Whewview custom_wv;
    private int  flag = 0;

    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){

            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        toolbar = (Toolbar) getActivity().findViewById(R.id.heard_main_toolbar);
        toolbar.setTitle("心率测试");
        toolbar.setTitleMarginStart(35);
        toolbar.setTitleTextColor(Color.parseColor("#ffffff"));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flag!=0) {
                    customStop();
                }
                heart_main_Fragment fragment =new heart_main_Fragment();
                FragmentManager fm =getActivity().getFragmentManager();
                FragmentTransaction ft =fm.beginTransaction();
                //实现fragment 切换效果
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.replace(R.id.fragment_heart,fragment).commit();

            }
        });
        //-----------------------------
        View view= inflater.inflate(R.layout.fragment_heart_heartrate_, container, false);
        mSurfaceView= (SurfaceView) view.findViewById(R.id.sv_msurfaceview);
        iv_heartrate_videotape= (ImageView) view.findViewById(R.id.iv_heartrate_videotape);
        tv_bmp_start= (TextView) view.findViewById(R.id.tv_bmp_start);
        tv_bmp_value= (TextView) view.findViewById(R.id.tv_bmp_value);
        custom_wv= (Whewview) view.findViewById(R.id.custom_whewview);


        //设置可以半透明显示
        getActivity().getWindow().setFormat(PixelFormat.TRANSLUCENT);
        SurfaceHolder holder =mSurfaceView.getHolder();   //取得holder
        holder.addCallback(this);  //holder 加入回调接口

        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        //重写AutofocusCallback接口
        mAutoFocusCallback=new Camera.AutoFocusCallback() {
            @Override
            public void onAutoFocus(boolean success, Camera camera) {
                if(success){
                    Log.i(TAG, "AutoFocus: success...");
                }else {
                    Log.i(TAG, "AutoFocus: failure...");
                }
            }
        };

        return view;
    }

    @Override
    public void surfaceCreated(final SurfaceHolder holder) {
        initCamera();
        mSurfaceHolder = holder;
        iv_heartrate_videotape.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                flag=1;
                custom_wv.start();
                myCamera.startPreview();
                // TODO Auto-generated method stub
                myParameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                myCamera.setParameters(myParameters);
                if (!mStartedFlg) {
                    // Start
                    if (mRecorder == null) {
                        mRecorder = new MediaRecorder(); // Create MediaRecorder
                    }
                    try {
                        tv_bmp_start.setText("录制中");
                        myCamera.unlock();
                        mRecorder.setCamera(myCamera);
                        // Set audio and video source and encoder
                        // 这两项需要放在setOutputFormat之前
                        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                        mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
                        mRecorder.setOrientationHint(90);
                        mRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_720P));
                        mRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());

                        // Set output file path
                        String path = getSDPath();
                        if (path != null) {

                            File dir = new File(path + "/VideoRecorderTest");
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            path = dir + ".mp4";
                            mRecorder.setOutputFile(path);
                            Log.d(TAG, "bf mRecorder.prepare()");
                            mRecorder.prepare();
                            Log.d(TAG, "af mRecorder.prepare()");
                            Log.d(TAG, "bf mRecorder.start()");
                            mRecorder.start();   // Recording is now started
                            Log.d(TAG, "af mRecorder.start()");
                            mStartedFlg = true;
//                            Timer timer =new Timer();
//                            timer.schedule(new TimerTask() {
//                                @Override
//                                public void run() {
//                                    custom_wv.stop();
//                                    customStop();
//                                }
//                            },5000);
                              Handler handler =new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    custom_wv.stop();
                                    customStop();
                                }
                            },5000);
                            //5秒进行延时操作

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                        } else {

                        }
                    }

        });
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        mSurfaceHolder = holder;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // surfaceDestroyed的时候同时对象设置为null
        mSurfaceView = null;
        mSurfaceHolder = null;
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }

    }

    public void initCamera()
    {
        if(myCamera == null && !isView)
        {
            myCamera = Camera.open();
            Log.i(TAG, "camera.open");
        }
        if(myCamera != null && !isView) {
            try {

                myParameters = myCamera.getParameters();
                myParameters.setPreviewSize(1280, 960);
                myParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
                myCamera.setParameters(myParameters);
                myCamera.setPreviewDisplay(mSurfaceHolder);
                myCamera.setDisplayOrientation(90);
                myCamera.startPreview();
                isView = true;
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
    }

    public String getSDPath(){
        return getActivity().getFilesDir().getPath();
    }

    public void customStop(){
        if (mStartedFlg) {
            try {
                myParameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                myCamera.setParameters(myParameters);
                tv_bmp_start.setText("开始");
                mRecorder.stop();
                mRecorder.reset();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mStartedFlg = false;
        //取消预览
        myCamera.stopPreview();



    }
}
